package com.ja.sevice.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.ja.config.WebsiteStateConfig;
import com.ja.dao.AgentMapper;
import com.ja.dao.UserMapper;
import com.ja.domain.AgentRecord;
import com.ja.domain.AgentTotal;
import com.ja.domain.Agents;
import com.ja.domain.PagingData;
import com.ja.domain.SetupAgent;
import com.ja.domain.TodayRecord;
import com.ja.domain.User;
import com.ja.sevice.AgentService;
import com.ja.sevice.YunyingbbService;
import com.ja.util.DateUtil;
import com.ja.util.JsonResult;

public class AgentServiceImpl implements AgentService {

	@Autowired
	private AgentMapper agentMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private YunyingbbService yunyingbbService;

	@Override
	public String insertAgentSetup(SetupAgent setupAgent) {
		setupAgent.setCreated_time(DateUtil.getCurrTime());
		int num = agentMapper.insertAgentSetup(setupAgent);
		String message = "添加失败,请稍后再试";
		if(num==1) {
			message = "恭喜你,添加成功";
		}
		return message;
	}

	@Override
	public String updateAgentSetup(SetupAgent setupAgent) {
		setupAgent.setCreated_time(DateUtil.getCurrTime());
		int num = agentMapper.updateAgentSetup(setupAgent);
		String message = "修改失败,请稍后再试";
		if(num==1) {
			message = "恭喜你,修改成功";
		}
		return message;
	}

	@Override
	public String deleteAgentSetup(Integer id) {
		int num = agentMapper.deleteAgentSetup(id);
		String message = "删除失败,请稍后再试";
		if(num==1) {
			message = "恭喜你,删除成功";
		}
		return message;
	}

	@Override
	public List<SetupAgent> findAgentSetup() {
		return agentMapper.findAgentSetup();
	}

	@Override
	public String findAgentRecord(PagingData paging, String startDate, String endDate, String userName,
			String agentName) {
		if(Integer.parseInt(WebsiteStateConfig.configs.get("agent_flag"))==1) {
			paging.setAllCount(agentMapper.findAgentRecordCount(startDate, endDate, userName, agentName));
			paging.setList(agentMapper.findAgentRecord(paging.getStartIndex(), paging.getLineCount(), startDate, endDate, userName, agentName));
		}else {
			paging.setAllCount(agentMapper.findAgentRecordCountTwo(startDate, endDate, userName, agentName));
			paging.setList(agentMapper.findAgentRecordTwo(paging.getStartIndex(), paging.getLineCount(), startDate, endDate, userName, agentName));
		}
		return PagingData.pagingData(paging);
	}

	/**
	 * 方法名：checkLotters 
	 * 描述：    查出所有的下级                  
	 * 参数：    @param agent 上级包含的所有下级
	 * 参数：    @return 
	 * @return: int
	 */
	int index = 0;
	List<Agents> agents = new ArrayList<Agents>();
	public List<Agents> findNodes(Agents agent) {
		String value = "";
		if (index == 0) {
			agents = null;
			agents = new ArrayList<>();
		}
		for (int i = 0; i < agent.getChild_list().size(); i++) {
			index++;
			Agents agent1 = agent.getChild_list().get(i);
			agent1.setAgent_grade(index);
			agents.add(agent1);
			findNodes(agent1);
			if (!value.equals(i + "")) {
				index = 0;
			}
			value = i + "";
		}
		index = 0;
		return agents;
	}
	
	@Override
	public List<AgentTotal> findOneAgent(Integer startIndex, Integer lineCount, Integer user_id, int type) {
		List<AgentTotal> agentTotal = new ArrayList<>();
		List<User> users = agentMapper.findAllOneAgent(startIndex,lineCount,user_id,type);
		for(User user : users) {
			AgentTotal total = new AgentTotal();
			double rebate = agentMapper.findAgentSumRebate(user.getId(),user_id);
			List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user.getId()));
			double sumBalance = 0.00;
			for(Agents agents : agentsList) {
				sumBalance += agents.getBalance();
			}
			TodayRecord record = yunyingbbService.findOperateRecord("", "", user.getName(),2);
			double chongzhi  = record.getChongzhi();//充值
			double tikuan  = record.getTikuan();//提款
			double touzhu  = record.getTouzhu();//投注
			
			total.setUser_name(user.getName());
			total.setAgent_grade(1);
			total.setRebate_money(rebate);
			total.setState(agentsList.size()+1);
			total.setBalance(sumBalance+user.getBalance());
			total.setOne_money(user.getBalance());
			total.setOne_recharge(chongzhi);
			total.setOne_drawing(tikuan);
			total.setOne_betting(touzhu);
			total.setUser_id(user.getId());
			agentTotal.add(total);
		} 
		return agentTotal;  
	}

	@Override
	public List<AgentTotal> findAllAgent(Integer agent_id, Integer user_id) {
		List<AgentTotal> agentTotal = new ArrayList<>();
		List<Agents> agentsList = findNodes(agentMapper.findAllNodes(agent_id));
		for (Agents agent : agentsList) {
			AgentTotal total = new AgentTotal();
			double rebate = agentMapper.findAgentSumRebate(agent.getUser_id(),user_id);
			User user1 = userMapper.getUserByid(agent.getUser_id());
			TodayRecord record = yunyingbbService.findOperateRecord("", "", user1.getName(),2);
			double chongzhi  = record.getChongzhi();//充值
			double tikuan  = record.getTikuan();//提款
			double touzhu  = record.getTouzhu();//投注
			
			total.setUser_name(agent.getUser_name());
			total.setAgent_grade(agent.getAgent_grade());
			total.setRebate_money(rebate);
			total.setOne_money(agent.getBalance());
			total.setOne_recharge(chongzhi);
			total.setOne_drawing(tikuan);
			total.setOne_betting(touzhu);
			total.setUser_id(agent.getUser_id());
			agentTotal.add(total);
		}
		return agentTotal;
	}

	@Override
	public List<AgentTotal> findAgentInfo(String name, Integer agent_id, Integer grade) {
		List<AgentTotal> agentTotal = new ArrayList<>();
		List<AgentTotal> agents = new ArrayList<>();
		List<Agents> agentsList = findNodes(agentMapper.findAllNodes(agent_id));
		for (Agents agent : agentsList) {
			User user1 = userMapper.getUserByid(agent.getUser_id());
			TodayRecord record = yunyingbbService.findOperateRecord("", "", user1.getName(),2);
			double chongzhi  = record.getChongzhi();//充值
			double tikuan  = record.getTikuan();//提款
			double touzhu  = record.getTouzhu();//投注
			
			AgentTotal total = new AgentTotal();
			total.setUser_name(agent.getUser_name());
			total.setAgent_grade(agent.getAgent_grade());
			total.setRebate_money(agentMapper.findAgentSumRebate(agent.getUser_id(), agent_id));
			total.setOne_money(agent.getBalance());
			total.setOne_recharge(chongzhi);
			total.setOne_drawing(tikuan);
			total.setOne_betting(touzhu);
			total.setUser_id(agent.getUser_id());
			agentTotal.add(total);
		}

		for (AgentTotal agent1 : agentTotal) {
			if (!"".equals(name) && grade != 0) {
				if (name.equals(agent1.getUser_name()) && grade == agent1.getAgent_grade()) {
					agents.add(agent1);
				}
			} else {
				if (grade == 0) {
					if (name.equals(agent1.getUser_name())) {
						agents.add(agent1);
					}
				} else {
					if(grade==agent1.getAgent_grade()) {
						agents.add(agent1);
					}
				}
			}
		}
		return agents;
	}

	@Override
	public List<AgentRecord> findAgentRebateInfo(Integer startIndex, Integer lineCount, String startDate,
			String endDate, Integer agent_id, int model) {
		List<AgentRecord> record = agentMapper.findAgentRebateInfo(startIndex, lineCount, startDate, endDate, agent_id, model);
		return record;
	}

	@Override
	public AgentTotal findAgentRebateSum(String startDate, String endDate, Integer user_id) {
		AgentTotal tAgentTotal = agentMapper.findAgentRebateSum(startDate, endDate, user_id);
		tAgentTotal.setOne_money(userMapper.getUserByid(user_id).getMoney());
		return tAgentTotal;
	}

	@Override
	public TodayRecord findAllTeamRcord(String startDate, String endDate, Integer user_id) {
		double touzhu =0.00;
		double paijiang =0.00;
		double chongzhi =0.00;
		double tikuan =0.00;
		double qipaitouzhu =0.00;
		double qipaipaijiang =0.00;
		TodayRecord datas = new TodayRecord();
		List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user_id));
		for(Agents agent : agentsList) {
			TodayRecord record = yunyingbbService.findOperateRecord("", "", agent.getUser_name(),2);
			touzhu += record.getTouzhu();//投注
			paijiang += record.getPaijiang();//派奖
			chongzhi += record.getChongzhi();//充值
			tikuan += record.getTikuan();//提款
			qipaitouzhu+=record.getQipaiBetting();
			qipaipaijiang+=record.getQipaiAwards();
		}
		datas.setCptouzhu(touzhu);
		datas.setCppaijiang(paijiang);
        datas.setZxchongzhi(chongzhi);
        datas.setZxtikuan(tikuan);
        datas.setQipaiBetting(qipaitouzhu);
        datas.setQipaiAwards(qipaipaijiang);
        datas.setBd_money(paijiang+qipaipaijiang-touzhu-qipaitouzhu);
		return datas;
	}

	@Override
	public Double receiveAReturnPoint() {
		return agentMapper.receiveAReturnPoint();
	}

	@Override
	public Integer findAgentRebateInfoCounts(PagingData paging) {
		return agentMapper.findAgentRebateInfoCounts(paging);
	}
	
	@Override
	public List<User> findAllNodes(Integer id) {
		List<User> users = new ArrayList<>();
		List<Agents> agentsList = findNodes(agentMapper.findAllNodes(id));
		for(Agents agent : agentsList) {
			User user = userMapper.getUserByid(agent.getUser_id());
			users.add(user);
		}
		return users;
	}
	
	@Override
	public User findUserSuperior(Integer agent_id) {
		return userMapper.findUserSuperior(agent_id);
	}
	
	@Override
	public Integer findAllAgentsCounts() {
		return agentMapper.findAllAgentsCounts();
	}
	
	@Override
	public List<User> findAllAgents(PagingData paging) {
		List<User> u =  agentMapper.findAllAgents(paging);
		for (User u1 : u) {//查询他下级
			List<Agents> agentsList = findNodes(agentMapper.findAllNodes(u1.getId()));
			u1.setState(agentsList.size());/* state是后端的状态  在这个接口里面没有用到所以暂时用来放下级代理人数 */
		}
		return u;
	}
	
	@Override
	public Integer findAgentTotalCounts(Integer id) {
		return agentMapper.findAgentTotalCounts(id); 
	}
	
	@Override
	public List<User> findAgentTotals(PagingData paging) {
		return agentMapper.findAgentTotals(paging);
	}
	
	@Override
	public Integer findAgentDetailsCounts(Integer user_id, String type) {
		return agentMapper.findAgentDetailsCounts(user_id, type);
	}
	
	@Override
	public List<TodayRecord> findAgentDetails(PagingData paging) {
		return agentMapper.findAgentDetails(paging);
	}
	
	@Override
	public SetupAgent findByIdAgentSetup(Integer id) {
		return agentMapper.findByIdAgentSetup(id);
	}
	
	@Override
	public int updateDailiRule(String rule, String rules) {
		return agentMapper.updateDailiRule(rule, rules);
	}

	@Override
	public String findAgentTeamRebate(PagingData paging,User user, String startTime, String endTime,Integer type) {
		if(type==1) {
			List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user.getId()));
			List<AgentRecord> rebate = agentMapper.findByIdTimeAgentRebateTotalTwo(user.getId(),DateUtil.findLatelyDate(-1),
			DateUtil.findFormatDate(),startTime,endTime);//昨日返点--今日返点 以及某个时间区间范围内的返点
			paging.setData(rebate);
			paging.setReplace1(agentsList.size()+"");
			return PagingData.pagingData(paging);
		}else {
			List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user.getId()));
			List<AgentRecord> rebate = agentMapper.findByIdTimeAgentRebateTotalTwo(user.getId(),DateUtil.findLatelyDate(-1),
					DateUtil.findFormatDate(),startTime,endTime);//昨日返点--今日返点 以及某个时间区间范围内的返点
			int allCount = agentMapper.findAgentRecordCountTwo(startTime, endTime, "", user.getName());//总记录数
			List<AgentRecord> records = agentMapper.findAgentRecordTwo(paging.getStartIndex(), paging.getLineCount(), startTime, endTime, "", user.getName());
			paging.setAllCount(allCount);
			paging.setList(records);
			paging.setData(rebate);
			paging.setReplace1(agentsList.size()+"");
			return PagingData.pagingData(paging);
		}
	}

	@Override
	public JsonResult findAgentTeamReport(User user,String time) {
		TodayRecord todayRecord = new TodayRecord();
		List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user.getId()));
		DecimalFormat dec = new DecimalFormat("#0.00");
		double touzhu =0.00;
		double paijiang =0.00;
		double huodong =0.00;
		double qipaitouzhu =0.00;
		double qipaipaijiang =0.00;
		double chongzhi =0.00;
		double tikuan =0.00;
		double tuanduiyue = 0.00;
		double teamRebate = 0.00;
		String ids = "";
		for(Agents agent : agentsList) {
			ids+=agent.getUser_id()+",";
			TodayRecord record = new TodayRecord();
			//今天--昨天--本月
			if(DateUtil.findFormatDate().equals(time)||DateUtil.findLatelyDate(-1).equals(time)||DateUtil.getLast12Months(0).equals(time)) {
				record = yunyingbbService.findOperateRecord(time,"",agent.getUser_name(),1);
				//上月
			}else if(DateUtil.getLast12Months(1).equals(time)) {
				record = yunyingbbService.findOperateRecord(time,"",agent.getUser_name(),3);
			}
			touzhu  += record.getTouzhu();//投注
			paijiang += record.getPaijiang();//派奖
			huodong += record.getHuodong();//活动
			qipaitouzhu += record.getQipaiBetting(); //棋牌投注
			qipaipaijiang += record.getQipaiAwards();//棋牌派奖
			chongzhi += record.getChongzhi();//充值
			tikuan += record.getTikuan();//提款
			teamRebate +=record.getDlfandian();//团队返佣
			tuanduiyue += agent.getBalance();//团队余额
		}  
		//充值人数
		int rechargeCount = 0;
		//注册人数
		int registerCount = 0;
		//投注人数
		int bettingCount=0;
		//团队亏盈
		double teamTotal = 0.00;
		//返点佣金
		double agentRebate= 0.00;
				
		if(agentsList.size()>0) {
			ids = ids.substring(0,ids.length()-1);
			//充值人数
			rechargeCount = agentMapper.findByTimeAndIdRechargeCount(time,ids);
			//注册人数
			registerCount = agentMapper.findByTimeAndIdRegisterCount(time,ids);
			//投注人数
			bettingCount = agentMapper.findByTimeAndIdBettingCount(time,ids);
			//团队亏盈
			teamTotal = paijiang+qipaipaijiang-touzhu-qipaitouzhu+huodong+teamRebate;
			//返点佣金
			agentRebate = agentMapper.findByIdTimeAgentRebateTwo(user.getId(), time);
		}
		todayRecord.setCptouzhu(touzhu);
		todayRecord.setCppaijiang(paijiang);
		todayRecord.setHuodong(huodong);
		todayRecord.setQipaiBetting(qipaitouzhu);
		todayRecord.setQipaiAwards(qipaipaijiang);
		todayRecord.setQipaisy(dec.format(qipaipaijiang-qipaitouzhu));
		todayRecord.setZxchongzhi(chongzhi);
		todayRecord.setZxtikuan(tikuan);
		todayRecord.setTuanduiyue(tuanduiyue);
		todayRecord.setRechargeCount(rechargeCount);
		todayRecord.setRegisterCount(registerCount);
		todayRecord.setOrderCount(bettingCount);
		todayRecord.setTeamRebate(teamRebate);
		todayRecord.setTeamTotal(teamTotal);
		todayRecord.setAgentRebate(agentRebate);
		todayRecord.setAgentCount(agentsList.size());
		return new JsonResult("success",todayRecord);
	}

	@Override
	public JsonResult findAgentSubordinateReport(User user, String userName, String time) {
		double touzhu  = 0.00;//投注
		double paijiang = 0.00;//派奖
		double chongzhi  = 0.00;//充值
		double tikuan  = 0.00;//提款
		double fandian = 0.00;//代理返点
		//double fanshui = 0.00;//返水
		double huodong = 0.00;//活动
		double qipaitouzhu = 0.00;//棋牌投注
		double qipaipaijiang = 0.00;//棋牌派奖
		double qipaisy = qipaipaijiang - qipaitouzhu;//棋牌输赢
		double qubusy = paijiang - touzhu + huodong +fandian + qipaisy;//全部输赢
		 List<Agents> agentsList = findNodes(agentMapper.findAllNodes(user.getId()));
		 List<AgentTotal> agentTotal = new ArrayList<>();
		for(Agents agent : agentsList) {
			TodayRecord record = new TodayRecord();
			if("".equals(userName)) {
				record = yunyingbbService.findOperateRecord(time,"",agent.getUser_name(),1);
				 touzhu  = record.getTouzhu();//投注
				 paijiang = record.getPaijiang();//派奖
				 chongzhi  = record.getChongzhi();//充值
				 tikuan  = record.getTikuan();//提款
				 fandian = record.getDlfandian();//代理返点
				//double fanshui = record.getFanshui();//返水
				 huodong = record.getHuodong();//活动
				 qipaitouzhu = record.getQipaiBetting();//棋牌投注
				 qipaipaijiang = record.getQipaiAwards();//棋牌派奖
				 qipaisy = qipaipaijiang - qipaitouzhu;//棋牌输赢
				 qubusy = paijiang - touzhu + huodong +fandian + qipaisy;//全部输赢
				
				AgentTotal total = new AgentTotal();
				total.setUser_name(agent.getUser_name());
				total.setAgent_grade(agent.getAgent_grade());
				total.setOne_betting(touzhu);
				total.setOne_award(paijiang);
				total.setOne_recharge(chongzhi);
				total.setOne_drawing(tikuan);
				total.setRebate_money(fandian);
				total.setOne_activity(huodong);
				total.setOne_chessCard_total(qipaisy);
				total.setOne_whole_total(qubusy);
				total.setOne_money(agent.getBalance());
				total.setUser_id(agent.getUser_id());
				agentTotal.add(total);
			}else {  
				if(userName.equals(agent.getUser_name())) {
					record = yunyingbbService.findOperateRecord(time,"",agent.getUser_name(),1);
					 touzhu  = record.getTouzhu();//投注
					 paijiang = record.getPaijiang();//派奖
					 chongzhi  = record.getChongzhi();//充值
					 tikuan  = record.getTikuan();//提款
					 fandian = record.getDlfandian();//代理返点
					//double fanshui = record.getFanshui();//返水
					 huodong = record.getHuodong();//活动
					 qipaitouzhu = record.getQipaiBetting();//棋牌投注
					 qipaipaijiang = record.getQipaiAwards();//棋牌派奖
					 qipaisy = qipaipaijiang - qipaitouzhu;//棋牌输赢
					 qubusy = paijiang - touzhu + huodong +fandian + qipaisy;//全部输赢
					
					AgentTotal total = new AgentTotal();
					total.setUser_name(agent.getUser_name());
					total.setAgent_grade(agent.getAgent_grade());
					total.setOne_betting(touzhu);
					total.setOne_award(paijiang);
					total.setOne_recharge(chongzhi);
					total.setOne_drawing(tikuan);
					total.setRebate_money(fandian);
					total.setOne_activity(huodong);
					total.setOne_chessCard_total(qipaisy);
					total.setOne_whole_total(qubusy);
					total.setOne_money(agent.getBalance());
					total.setUser_id(agent.getUser_id());
					agentTotal.add(total);
				}
			}
		} 
		return new JsonResult("1",agentTotal);
	}

	

}
